<template>
  <view class="flow-container">
    <!-- 顶部导航栏 -->
    <view class="nav-header">
      <view class="nav-back" @tap="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
      </view>
      <view class="nav-title">资金流水</view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 分类选项卡 -->
    <view class="tab-container">
      <view class="tab-item" :class="{'tab-active': tabActive === 'all'}" @tap="switchTab('all')">
        <text>全部</text>
      </view>
      <view class="tab-item" :class="{'tab-active': tabActive === 'income'}" @tap="switchTab('income')">
        <text>收入</text>
      </view>
      <view class="tab-item" :class="{'tab-active': tabActive === 'expense'}" @tap="switchTab('expense')">
        <text>支出</text>
      </view>
    </view>
    
    <!-- 记录列表 -->
    <view class="flow-list" v-if="filteredRecords.length > 0">
      <view class="flow-item" v-for="(item, index) in filteredRecords" :key="index">
        <view class="flow-info">
          <view class="flow-title">{{item.paymentMethod || '未知交易'}}</view>
          <view class="flow-time">{{formatDate(item.createdAt || item.createTime) || '未知时间'}}</view>
        </view>
        <view class="flow-amount" :class="{'income-amount': item.paymentMethod === '余额充值', 'expense-amount': item.paymentMethod !== '余额充值'}">
          <text>{{item.paymentMethod === '余额充值' ? '+' : '-'}}{{item.amount || 0}}</text>
        </view>
      </view>
    </view>
    
    <!-- 空记录提示 -->
    <view class="empty-flow" v-else>
      <image class="empty-icon" src="/static/images/empty-record.png" mode="aspectFit"></image>
      <text class="empty-text">暂无记录</text>
    </view>
  </view>
</template>

<script>
import uIcon from "uview-ui/components/u-icon/u-icon.vue"
import request from '@/util/request.js'

export default {
  components: {
    uIcon
  },
  data() {
    return {
      userInfo: {
        userId: '',
        userAcc: '',
        userName: ''
      },
      records: [],
      tabActive: 'all', // all, income, expense
      loading: false
    }
  },
  computed: {
    filteredRecords() {
      if (this.tabActive === 'all') {
        return this.records;
      } else if (this.tabActive === 'income') {
        return this.records.filter(item => item.paymentMethod === '余额充值');
      } else {
        return this.records.filter(item => item.paymentMethod !== '余额充值');
      }
    }
  },
  onLoad() {
    // 设置状态栏样式
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    });
    
    this.getUserInfo();
    this.getPaymentRecords();
  },
  methods: {
    goBack() {
      wx.navigateBack();
    },
    
    // 切换选项卡
    switchTab(tab) {
      this.tabActive = tab;
    },
    
    // 获取用户信息
    getUserInfo() {
      try {
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
          this.userInfo.userId = userInfo.userId;
          this.userInfo.userAcc = userInfo.userAcc;
          this.userInfo.userName = userInfo.userName;
        } else {
          // 未登录处理
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      } catch (e) {
        console.error('获取用户信息失败', e);
      }
    },
    
    // 获取资金流水
    async getPaymentRecords() {
      if (!this.userInfo.userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      wx.showLoading({
        title: '加载中...'
      });
      
      try {
        const res = await request({
          url: '/user-service/user/paymentRecords',
          method: 'GET',
          data: {
            userId: this.userInfo.userId
          }
        });
        
        wx.hideLoading();
        this.loading = false;
        
        // console.log('资金流水原始数据:', res);
        
        if (res.code === 200 && res.data) {
          this.records = res.data.records || [];
          // console.log('处理后的资金流水:', this.records);
          
          // 检查日期字段
          if (this.records.length > 0) {
            console.log('第一条记录日期字段:', {
              createdAt: this.records[0].createdAt,
              createTime: this.records[0].createTime
            });
          }
        } else {
          wx.showToast({
            title: '获取记录失败',
            icon: 'none'
          });
        }
      } catch (error) {
        wx.hideLoading();
        this.loading = false;
        console.error('获取资金流水失败', error);
        
        wx.showToast({
          title: '获取记录失败',
          icon: 'none'
        });
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未知时间';
      
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '未知时间';
        
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hour = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes().toString().padStart(2, '0');
        
        return `${year}-${month}-${day} ${hour}:${minute}`;
      } catch (e) {
        console.error('日期格式化错误', e);
        return '未知时间';
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.flow-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-header {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #ffffff;
  padding: 80rpx 30rpx;
  
  .nav-back {
    width: 60rpx;
    display: flex;
    align-items: center;
  }
  
  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
  
  .nav-right {
    width: 60rpx;
  }
}

.tab-container {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
  padding: 10rpx 0;
}

.tab-active {
  color: #4CAF50;
  font-weight: 500;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background-color: #4CAF50;
    border-radius: 2rpx;
  }
}

.flow-list {
  padding: 20rpx;
}

.flow-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flow-info {
  flex: 1;
}

.flow-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
}

.flow-time {
  font-size: 24rpx;
  color: #999;
}

.flow-amount {
  font-size: 36rpx;
  font-weight: bold;
}

.income-amount {
  color: #4CAF50;
}

.expense-amount {
  color: #F44336;
}

.empty-flow {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style> 